package com.dcsgo.myTankGameClient.test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * @author DCSGO
 * @version 1.0
 * 通过键盘控制小球的移动
 * Java的事件控制
 */
public class BallMove extends JFrame {
    BallPanel mp = null;

    public static void main(String[] args) {
        BallMove ballMove = new BallMove();
    }

    public BallMove() {
        this.mp = new BallPanel();
        this.add(mp);
        this.setSize(400, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //添加键盘监听器 用于监听 面版 mp
        this.addKeyListener(mp);
    }
}

//监听键盘实际需要实现 KeyListener 接口
class BallPanel extends JPanel implements KeyListener {
    //绘制小球的位置
    private int x;
    private int y;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x, y, 20, 20);
    }

    @Override //监听键盘输入 当键盘有字符输入时会调用该方法
    public void keyTyped(KeyEvent e) {

    }

    @Override //监听键盘上的按键被按下 当键盘有按键被按下时会调用该方法
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_W) {//上
            y -= 3;
        } else if (e.getKeyCode() == KeyEvent.VK_S) {//下
            y += 3;
        } else if (e.getKeyCode() == KeyEvent.VK_A) {//左
            x -= 3;
        } else if (e.getKeyCode() == KeyEvent.VK_D) {//右
            x += 3;
        }

        //在键盘进行操作后重绘面板
        repaint();
    }

    @Override //监听键盘上的按键被释放 当键盘有按键被松开时会调用该方法
    public void keyReleased(KeyEvent e) {

    }
}